<template>
    <div v-move class="chat-box">
      <div class="header">
        <i @click="clickIcon(msgListHeight)" :class="msgListHeight==50?'el-icon-caret-top':'el-icon-caret-bottom'"></i>
      </div>
      <div ref="msgListRef" @scroll="scrollGet($event,1)" :style="{
        'height': msgListHeight+'px'
      }" class="msg-list-style">
        <div :style="{
          'text-align': item.userName?'left':'right'
        }" v-for="(item,index) in msgList" :key="index">
          <pre v-if="item.userName" class="msg-list-name">{{item.userName}}:</pre>
          <pre class="msg-list-item">{{item.message}}</pre>
        </div>
      </div>
      <div style="display: flex;padding: 5px;">
<!--        type="textarea" :rows="1" resize="none" autosize-->
        <el-input style="flex: 1;" placeholder="请输入内容" v-model="msg"
                  size="mini"
                  @keyup.enter.native="send(msg)">
        </el-input>
        <el-button @click="send(msg)" size="mini">发送</el-button>
      </div>
    </div>
</template>

<script>
    export default {
      name: "ChatInputBox",
      data(){
          return {
            msg: '',
            msgList: [],
            msgListHeight: 50,
            scrollTop: 0,// 【展示】是否滚动
          }
      },
      methods:{
        clickIcon(msgListHeight){
          this.msgListHeight = msgListHeight==50?500:50;
          this.scrollToBottom();
        },
        send(msg){
          if(!msg){
            return;
          }
          this.msgList.push({
            message: msg
          });
          this.msg = '';
          this.scrollToBottom();
          this.$emit('msg',msg);
        },
        //【滚动条】滚动到底部
        scrollToBottom() {
          // this.$nextTick 将回调延迟到下次DOM更新循环之后执行。在修改数据之后立即使用它，然后等待DOM更新
          this.$nextTick(() => {
            // dom 元素更新后执行滚动条到底部 否则不生效
            let scrollElem = this.$refs.msgListRef;
            if(this.scrollTop == scrollElem.scrollTop){
              // scrollElem.scrollTop = scrollElem.scrollHeight
              scrollElem.scrollTo({
                top: scrollElem.scrollHeight,
                behavior: 'smooth'
              });
            }
          });
        },
        //【滚动条】判断是否在滚动
        scrollGet(e) {
          const { scrollTop } = e.srcElement;
          this.scrollTop = scrollTop;
        },
        // 接收消息
        messageReceive(data){
          this.msgList.push(data);
          this.scrollToBottom();
        }
      },
      directives: {
        // 自定义移动指令：https://www.jianshu.com/p/e15246302e06
        move(el) {
          // console.log(el)
          // console.dir(el)
          el.onmousedown = function (e) {

            //获取鼠标点击处分别与div左边和div上边的距离：鼠标位置-div位置
            let startX = e.clientX - el.offsetLeft,
              startY = e.clientY - el.offsetTop;

            throttle(
              (document.onmousemove = function (ev) {
                let event = ev || window.event;
                let moveX = event.clientX - startX,
                  moveY = event.clientY - startY;
                el.style.left = moveX + "px";
                el.style.top = moveY + "px";
              }),
              500
            );

            // 鼠标弹起时不再移动
            document.onmouseup = function () {
              document.onmousemove = null;
            };
          };
        },
      },
    }
    // 节流函数: 连续不断地触发某事件（如点击），只在单位时间内只触发一次
    // throttle和debounce均是通过减少实际逻辑处理过程的执行来提高事件处理函数运行性能的手段，并没有实质上减少事件的触发次数。
    function throttle(fun, delay=2000) {
      let last, deferTimer
      return function (args) {
        let that = this;
        let _args = arguments;

        let now = +new Date();

        if(last && now < last + delay) {
          clearTimeout(deferTimer);
          deferTimer = setTimeout(function () {
            last = now;
            fun.apply(that, _args);
          },delay)
        } else {
          last = now;
          fun.apply(that,_args);
        }
      }
    }
</script>

<style scoped>
  .header{
    text-align: right;
    border-bottom: 1px solid #f2f2f2;
  }
  .header i{
    background: #333333;
    border-radius: 10px;
    color: #ffffff;
    padding: 0 1px 1px 1px;
    margin-right: 10px;
  }
.chat-box{
  position: fixed;
  z-index: 10000;
  left: 0px;
  top: calc(100% - 120px);
  border-radius: 5px;
  width: 300px;
  background-color: #ffffff;
}
  .msg-list-style{
    overflow: auto;
  }
  .msg-list-name{
    display: inline-block;
    box-sizing: border-box;
    color: rgba(51, 51, 51, 0.49);
    margin: 1px 0;
    padding: 5px 0 5px 10px;
    text-align: left;
  }
  .msg-list-item{
    display: inline-block;
    box-sizing: border-box;
    border-radius: 5px;
    color: #333333;
    margin: 1px 0;
    padding: 5px 10px;
    border: 1px solid #f2f2f2;
    background-color: #8cc5ff;
    text-align: left;
  }
  /*滚动条*/
  ::-webkit-scrollbar {
    width: 7px;/*右边的滚动条宽度*/
    height: 7px;/*下方的滚动条高度*/
    /*background-color: red;!*滚动条背景*!*/
  }
  /*滑块*/
  ::-webkit-scrollbar-thumb {
    border: 1px solid #fff;
    border-radius: 6px;
    background: #c9c9c9; /*滑块颜色*/
  }
</style>
